Skip to content

1px

为什么有 1px 问题

物理像素[设备像素]

移动设备出厂时,不同设备自带的不同像素,也称硬件像素 UI 设计师要求的 1px 是指设备的物理像素 1px

逻辑像素[CSS 像素]

它们之间存在一个比例关系,通常可以用 javascript 中的 window.devicePixelRatio 来获取, 也可以用媒体查询的 -webkit-min-device-pixel-ratio 来获取。当然,比例多少与设备相关。

在手机上 border 无法达到我们想要的效果。 这是因为 devicePixelRatio 特性导致,iPhone 的 devicePixelRatio==2, 而 border-width: 1px; 描述的是设备独立像素,所以,border 被放大到物理像素 2px 显示,在 iPhone 上就显得较粗。

解决方法

  • css
css
.border {
  border: 1px solid #999;
}
@media screen and (-webkit-min-device-pixel-ratio: 2) {
  .border {
    border: 0.5px solid #999;
  }
}
@media screen and (-webkit-min-device-pixel-ratio: 3) {
  .border {
    border: 0.333333px solid #999;
  }
}
  • 媒体查询 scaleY
css
/* 2倍屏 */
@media only screen and (-webkit-min-device-pixel-ratio: 2) {
  .border-bottom::after {
    -webkit-transform: scaleY(0.5);
    transform: scaleY(0.5);
  }
}
/* 3倍屏 */
@media only screen and (-webkit-min-device-pixel-ratio: 3) {
  .border-bottom::after {
    -webkit-transform: scaleY(0.33);
    transform: scaleY(0.33);
  }
}

1px

在 MIT 许可下发布